package com.rankeiot.developer.interceptor;

import com.rankeiot.core.Current;
import com.rankeiot.core.data.UserInfo;
import com.rankeiot.core.exception.AuthException;
import com.rankeiot.core.util.IDUtil;
import com.rankeiot.core.util.TokenUtil;
import com.rankeiot.developer.DevelopMenu;
import com.rankeiot.platform.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.exception.MagicLoginException;
import org.ssssssss.magicapi.core.interceptor.Authorization;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;
import org.ssssssss.magicapi.core.model.Group;
import org.ssssssss.magicapi.core.model.MagicEntity;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletRequest;

@Component
@RequiredArgsConstructor
public class DeveloperAuthorizationInterceptor implements AuthorizationInterceptor {
    final UserService userService;

    /**
     * 配置是否需要登录
     */
    @Override
    public boolean requireLogin() {
        return true;
    }

    /**
     * 根据Token获取User
     */
    @Override
    public MagicUser getUserByToken(String token) throws MagicLoginException {
        if(token==null||"undefined".equals(token)||"unauthorization".equals(token)){
            throw new MagicLoginException("token无效");
        }
        ServletRequestAttributes attributes = getRequestAttributes();
        if (attributes == null) {
            UserInfo ui= Current.user(true,token,null,null);
            if(ui!=null){
                if(ui.getToken()==null)
                {
                   ui.setToken(token);
                }
                return create(ui);
            }
            throw new MagicLoginException("token无效");
        } else {
            Object user = attributes.getAttribute("@user_info_", 0);
            if (user != null) {
                UserInfo ui = (UserInfo) user;
                return create(ui);
            } else {
                HttpServletRequest request = attributes.getRequest();
                HttpServletResponse response = attributes.getResponse();
                try {
                    UserInfo ui = Current.user(true, token, request, response);
                    if (ui == null) {
                        throw new MagicLoginException("token无效");
                    }
                    return create(ui);
                } catch (AuthException e) {
                    throw new MagicLoginException(e.getMessage());
                }
            }
        }
    }

    @Override
    public MagicUser login(String username, String password) throws MagicLoginException {
        // 根据实际情况进行修改，如查询数据库。。
        UserInfo userInfo = userService.loadUserInfo(username, password);

        if (userInfo == null) {
            throw new MagicLoginException("用户名或密码不正确");
        }
        Current.login(userInfo);
        MagicUser magicUser = create(userInfo);
        return magicUser;
    }

    private MagicUser create(UserInfo userInfo) {
        String token = userInfo.getToken();
        long timeout = System.currentTimeMillis()+1800000;
        if(token!=null){
            timeout  = TokenUtil.getTime(token) * 1000;
        }
        String id = IDUtil.base64UUID()+ "|" + userInfo.getPassword();
        return new MagicUser(id, userInfo.getUsername(), token, timeout);
    }

    /**
     * 是否拥有页面按钮的权限
     */
    @Override
    public boolean allowVisit(MagicUser magicUser, MagicHttpServletRequest request, Authorization authorization) {
        // AuthInterceptor.checkPriv()
        // Authorization.SAVE 保存
        // Authorization.DELETE 删除
        // Authorization.VIEW 查询
        // Authorization.LOCK 锁定
        // Authorization.UNLOCK 解锁
        // Authorization.DOWNLOAD 导出
        // Authorization.UPLOAD 上传
        // Authorization.PUSH 推送
        UserInfo user = Current.user();
        switch (authorization) {
            case VIEW:
            case DOWNLOAD:
                return user.isSuper() || user.hasPermission(DevelopMenu.editor);
            case SAVE:
            case LOCK:
            case UNLOCK:
            case UPLOAD:
            case PUSH:
                return user.isSuper() || user.hasPermission(DevelopMenu.editor_EDIT);
            case DELETE:
                return user.isSuper() || user.hasPermission(DevelopMenu.editor_DELETE);
        }
        // Current.user().hasPermission()
        return true;
    }

    /**
     * 是否拥有对该接口的增删改权限
     * 此方法可以不重写，则走默认的 boolean allowVisit(MagicUser magicUser, MagicHttpServletRequest request, Authorization authorization) 方法
     */
    @Override
    public boolean allowVisit(MagicUser magicUser, MagicHttpServletRequest request, Authorization authorization, MagicEntity entity) {
        // Authorization.SAVE 保存
        // Authorization.DELETE 删除
        // Authorization.VIEW 查询
        // Authorization.LOCK 锁定
        // Authorization.UNLOCK 解锁
        // 自行写逻辑判断是否拥有如果有，则返回true，反之为false
        return true;
    }

    /**
     * 是否拥有对该分组的增删改权限
     * 此方法可以不重写，则走默认的 boolean allowVisit(MagicUser magicUser, MagicHttpServletRequest request, Authorization authorization) 方法
     */
    @Override
    public boolean allowVisit(MagicUser magicUser, MagicHttpServletRequest request, Authorization authorization, Group group) {

        // Authorization.SAVE 保存
        // Authorization.DELETE 删除
        // Authorization.VIEW 查询
        // 自行写逻辑判断是否拥有如果有，则返回true，反之为false
        return true;
    }

    private static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }
}
